#include "config.h"

#include "ms2lstat.h"

ECMBOOL	no_suffix_logging;

char	*logbase = "log";
static char	*suffix;

static void
setup_suffix(void)
{
	ecm_datetime_t	datetime;

	if (!ecm_empty_str(suffix))
		return;

	ecm_get_current_datetime(&datetime);

	ecm_asprintf(&suffix, "%02u%02u_%02u%02u%02u",
		     datetime.mon, datetime.mday,
		     datetime.hour, datetime.min, datetime.sec);
}

static ECMBOOL
try_to_make_directory(const char *logpath)
{
	char	*dirname;
	char	*path = ecm_strdup(logpath);
	ecm_err_t	err;

	dirname = ecm_dirname(path);
	if (ecm_strcmp(dirname, logpath) == 0) {
		ecm_free(path);
		return ECM_FALSE;
	}

	err = ecm_mkdir(dirname, ECM_P_ALLU);
	ecm_free(path);

	return (err == ECM_OK);
}

FILE *
setup_logging(const char *name)
{
	FILE	*logfp;
	char	*logpath;

	setup_suffix();

	if (no_suffix_logging)
		ecm_asprintf(&logpath, "%s_%s.log", logbase, name);
	else
		ecm_asprintf(&logpath, "%s_%s_%s.log", logbase, name, suffix);

	logfp = ecm_fopen(logpath, "a+");
	if (logfp == NULL) {
		if (try_to_make_directory(logpath)) {
			logfp = ecm_fopen(logpath, "a+");
		}
	}
	ecm_free(logpath);

	return logfp;
}

void
report_result(void)
{
	FILE	*fp;

	fp = setup_logging("general");

	ecm_fprintf(fp, "Total Number of Logs:               %I64u\n", n_logs);
	ecm_fprintf(fp, "Total Number of Error Logs:         %I64u\n", n_error_logs);

	report_request_result(fp);
	report_media_result(fp);
	report_client_result(fp);
	report_arrival_result(fp);
	report_session_result(fp);

	ecm_fclose(fp);
}
